package os.kai.aiu;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;

public class IncreaseWriter implements AutoCloseable {
    private final DecimalFormat fmt = new DecimalFormat("0000");
    private final String prefix;
    private final String suffix;
    private final String encoding;
    private int index;
    private PrintWriter writer;
    public IncreaseWriter(String prefix,String suffix,String encoding,int start) {
        this.prefix = prefix;
        this.suffix = suffix;
        this.encoding = encoding;
        index = start;
    }
    private void renew() throws IOException {
        if(writer!=null){
            writer.close();
        }
        writer = new PrintWriter(prefix+fmt.format(index)+suffix,encoding);
    }
    public void setIndex(int i) throws IOException {
        int diff = i-index;
        if(diff>0){
            //step on
            if(diff>1){
                System.err.println("index skipped: last="+index+", new="+i);
            }
            index = i;
            renew();
        }
        else if(diff<0){
            System.err.println("index decrease: last="+index+", new="+i);
        }
    }
    public void println(String line) {
        if(writer!=null){
            writer.println(line);
        }
    }
    public void flush() {
        if(writer!=null){
            writer.flush();
        }
    }
    @Override
    public void close() {
        if(writer!=null){
            writer.close();
            writer = null;
        }
    }
}
